from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from login import models,login_serializers
from utils.jwttool import tool
from django.core.cache import cache

class Login(APIView):
    def post(self,request):



        username=request.data.get('username')
        password=request.data.get('password')
        info=models.UserMode.objects.filter(username=username).first()
        # key='user_token'
        # redis_login=cache.get(key)#设置redis
        # token = str(tool.get_token(info.id))#传递token需要的id
        #
        # if redis_login:
        #     return Response({'msg': '登陆成功', 'code': 200 ,'data':{"token":token,'userid':info.id}})
        #


        if not info:
            return Response({'msg':'账号不存在','code':400})
        if info.password==password:
            #添加redis
            # cache.set(key,info.password,60*60*24)
            return Response({'msg': '登陆成功', 'code': 200 ,'data':{"token":token,'userid':info.id}})

        else:
            return Response({'msg': '密码错误', 'code': 400})


from django.core.files.storage import default_storage
class Uploads(APIView):
    def post(self,request):
        file=request.data.get('file')
        types=['png','jpg']
        if file.name.split('.')[-1] not in types:
            return Response({"code":401,'msg':'图片格式不符合要求'})
        if file.size>1024*1024*4:
            return Response({"code":402,'msg':'图片过大'})
        uploadfile=default_storage.save(file.name,file)#三个参数  文件位置，文件名字，文件对象
                                                #文件位置如果在setting中的MEDIA_URL中设置了就可以不写了如果变化在此基础上写
        url=default_storage.url(uploadfile) #生成一个可以被访问的url
        return Response({'url':url})

